package com.threeti.mecool.core.application.message;

import com.threeti.mecool.core.domain.model.message.SystemMessage;
import com.threeti.mecool.core.exception.MessageSendException;
import com.threeti.mecool.core.infrastructure.persistence.message.SystemMessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SystemMessageServiceImpl implements SystemMessageService {
    private SystemMessageRepository systemMessageRepository;

    @Autowired
    public void setSystemMessageRepository(SystemMessageRepository systemMessageRepository) {
        this.systemMessageRepository = systemMessageRepository;
    }

    @Override
    public void send(SystemMessage systemMessage) throws MessageSendException {
        systemMessageRepository.save(systemMessage);
    }

    @Override
    public void send(String creator, String receiver, String head, String body) throws MessageSendException {
        systemMessageRepository.save(new SystemMessage(receiver, head, body));
    }

    @Override
    public Page<SystemMessage> findUnreadMessages(String userLoginName, Pageable pageable) {
        Sort sort = pageable.getSort();
        if (sort == null) {
            sort = new Sort(Sort.Direction.DESC, "createdOn");
            pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        }
        return systemMessageRepository.findByReceiverAndReceived(userLoginName, 1, pageable);
    }

    @Override
    public Page<SystemMessage> findAllMessages(String userLoginName, Pageable pageable) {
        Sort sort = pageable.getSort();
        if (sort == null) {
            sort = new Sort(Sort.Direction.DESC, "createdOn");
            pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        }
        return systemMessageRepository.findByReceiver(userLoginName, pageable);
    }

    @Override
    public void markMessagesAsRead(long... messageIdArray) {
        Date now = new Date();
        for (long messageId : messageIdArray) {
            SystemMessage message = systemMessageRepository.findOne(messageId);
            if (message != null && (message.getReceived() == 0 || message.getReceivedOn() == null)) {
                message.setReceived(1);
                message.setReceivedOn(now);
                systemMessageRepository.save(message);
            }
        }
    }
}
